﻿#ifndef _RESULTCODE_H
#define _RESULTCODE_H


#include <QHttpServer>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonArray>


class ResultCode
{
	struct Code
	{
		int code;
		const char* codeStr;
		const char* message;
		Code(int code, const char* codeStr, const char* message)
			:code(code), codeStr(codeStr), message(message)
		{
		}

		QByteArray toJson() const
		{
			QJsonObject qobject;
			qobject.insert("code", code);
			qobject.insert("message", message);
			return QJsonDocument(qobject).toJson(QJsonDocument::Compact);
		}
		operator QJsonValue() const
		{
			return code;
		}

	};


public:

#define CODE(name,value,message) inline static Code name {value,#name, message}

	//链接提示：
	CODE(Success, 0, "success");
	CODE(NotSupport, 1, "不支持该操作");
	CODE(SuccessButNotData, 2, "成功，只是没有数据改变");

	//参数错误[1000~1999)
	CODE(ParamJsonInvalid, 1000,"请求json数据失败");
	CODE(ParamJsonParameterMissing, 1001,"请求的数据缺少参数");
	CODE(ParamParseError, 1002,"参数解析错误");

	//服务器错误[2000~2999)
	CODE(ServerSqlQueryError, 2000, "SQL语句执行失败");
	CODE(ServerInnerError, 2001, "文件保存失败");
	CODE(ServerResourceNotFound, 2003, "找不到资源");

	//用户错误[3000~3999)
	CODE(UserLoginError, 3000, "帐号或密码不正确");
	CODE(UserAccountIsEnable, 3001, "该帐户已被禁用");
	CODE(UserIdisExists, 3002, "已存在该id的帐户");
	CODE(UserUnauthorized, 3003, "Authorization”帐号未授权");
	CODE(UserAuthorizationFormatError, 3004, "账号授权格式错误，只支持使用承载方式Bearer");
	CODE(UserTokenInvalid, 3005, "帐户令牌(token)格式无效");
	CODE(UserTokenExpired, 3006, "令牌的帐户(token)格式已过期");


#undef CODE

	friend class Result;

};

class Result
{
public:
	static QByteArray success()
	{
		return ResultCode::Success.toJson();
	}
	static QByteArray success(const ResultCode::Code& code)
	{
		return code.toJson();
	}
	static QByteArray success(const QJsonObject& data)
	{
		QJsonObject qobject;
		qobject.insert("code", ResultCode::Success);
		qobject.insert("message", ResultCode::Success.message);
		qobject.insert("data", data);
		return QJsonDocument(qobject).toJson(QJsonDocument::Compact);
	}
	static QByteArray failure(const ResultCode::Code& code)
	{
		return code.toJson();
	}
	static QByteArray failure(const ResultCode::Code& code, const QString& message)
	{
		QJsonObject qobject;
		qobject.insert("data", ResultCode::Success);
		qobject.insert("message", message);
		return QJsonDocument(qobject).toJson(QJsonDocument::Compact);
	}

};


#endif